package com.lcm.jnode.handler;

import java.util.List;

import net.dreamlu.api.life.HelpApi;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.google.common.collect.Lists;
import com.gson.bean.Articles;
import com.gson.bean.InMessage;
import com.gson.bean.OutMessage;
import com.gson.inf.MessageProcessingHandler;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.lcm.jnode.kit.FetchKit;
import com.lcm.jnode.model.WxRule;

/**
 * 微信消息回复
 * @author L.cm
 * @date 2013-6-20 下午3:03:34
 */
public class WeChatMessageHandler implements MessageProcessingHandler {

	private static final Logger log = Logger.getLogger(WeChatMessageHandler.class);
    private static final String url = "http://sandbox.api.simsimi.com/request.p?key=647c1583-7aaa-4176-8df4-c92fcfccba9e&lc=ch&ft=1.0&text=";
    private static final String SQL = "SELECT r.reply FROM wx_rule r WHERE r.rule = ?";
    
    @Override
    public OutMessage eventTypeMsg(InMessage msg) {
        // Event subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
        // EventKey 事件KEY值，与自定义菜单接口中KEY值对应
        String event = msg.getEvent();
        OutMessage out = new OutMessage();
        String rule = "default";
        if(StringKit.isBlank(event)){
        } else if ("subscribe".equals(event.toLowerCase())){
        	rule = "subscribe";
        } else if ("unsubscribe".equals(event.toLowerCase())){
        	rule = "unsubscribe";
        } else if ("click".equals(event.toLowerCase())){
             String eventKey = msg.getEventKey();
        }
        Record ruleRecord = Db.findFirst(SQL, rule);
        out.setContent(ruleRecord.getStr(WxRule.REPLY));
        return out;
    }
    
    @Override
    public OutMessage imageTypeMsg(InMessage msg) {
        OutMessage out = new OutMessage();
        Record ruleRecord = Db.findFirst(SQL, "image");
        out.setContent(ruleRecord.getStr(WxRule.REPLY));
        return out;
    }
    
    @Override
    public OutMessage linkTypeMsg(InMessage msg) {
        OutMessage out = new OutMessage();
        Record ruleRecord = Db.findFirst(SQL, "link");
        out.setContent(ruleRecord.getStr(WxRule.REPLY));
        return out;
    }
    
    /** 返回天气 **/
    @Override
    public OutMessage locationTypeMsg(InMessage msg) {
        OutMessage out = new OutMessage();
        JSONArray arrayInfo = HelpApi.weather(msg.getLocationY() + "," + msg.getLocationX());
        List<Articles> list = Lists.newArrayList();
        for (Object object : arrayInfo) {
        	JSONObject json = JSONObject.fromObject(object);
        	Articles articles = new Articles();
        	articles.setPicUrl(json.getString("dayPictureUrl"));
        	StringBuffer sb = new StringBuffer();
        	sb.append(json.getString("date")).append(" ");
        	sb.append(json.getString("weather")).append(" ");
        	sb.append(json.getString("wind")).append(" ");
        	sb.append(json.getString("temperature"));
        	articles.setTitle(sb.toString());
        	articles.setDescription(sb.toString());
        	articles.setUrl("http://www.dreamlu.net");
        	list.add(articles);
		}
        out.setArticles(list);
        out.setArticleCount(list.size());
        out.setMsgType(MSG_TYPE_NEWS);
        return out;
    }
    
    @Override
    public OutMessage textTypeMsg(InMessage msg) {
    	OutMessage out = new OutMessage();
    	String content = msg.getContent();
    	if(StringKit.isBlank(content) || "：".equals(content) || ":".equals(content) || "#".equals(content)){
    		Record ruleRecord = Db.findFirst(SQL, "default");
            out.setContent(ruleRecord.getStr(WxRule.REPLY));
        } else if (content.startsWith(":") || content.startsWith("：")){
        	content = content.substring(1, content.length());
        	JSONArray jsonArray = HelpApi.translate(content);
        	StringBuffer outmsg = new StringBuffer();
        	for (Object object : jsonArray) {
        		outmsg.append(JSONObject.fromObject(object).getString("dst")).append("\t");
			}
        	out.setContent(outmsg.toString());
        } else if (content.startsWith("#")){
        	content = content.substring(1, content.length());
        	log.info(content);
        	Record ruleRecord = Db.findFirst(SQL, "leavemsg");
            out.setContent(ruleRecord.getStr(WxRule.REPLY));
        }else{
        	JSONObject josn = JSONObject.fromObject(FetchKit.doGet(url + content));
        	if(100 == josn.getInt("result")){
        	    out.setContent(josn.getString("response"));
        	}else{
        	    out.setContent("你发的什么啊，忽弄我这只鸡？");
        	}
        }
        return out;
    }

    @Override
    public OutMessage voiceTypeMsg(InMessage msg) {
        OutMessage out = new OutMessage();
        Record ruleRecord = Db.findFirst(SQL, "voice");
        out.setContent(ruleRecord.getStr(WxRule.REPLY));
        return out;
    }
}
